package com.ruoyi.questionnaire.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswer;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerSubmitDTO;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerVO;
import com.ruoyi.questionnaire.service.IQuestionnaireAnswerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import java.util.stream.Collectors;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswerDetail;

/**
 * 问卷答卷Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/questionnaire/answer")
public class QuestionnaireAnswerController extends BaseController
{
    @Autowired
    private IQuestionnaireAnswerService answerService;

    /**
     * 查询答卷列表
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:list')")
    @GetMapping("/list")
    public TableDataInfo list(QuestionnaireAnswer answer)
    {
        startPage();
        List<QuestionnaireAnswerVO> list = answerService.selectQuestionnaireAnswerVOList(answer);
        return getDataTable(list);
    }

    /**
     * 导出答卷列表
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:export')")
    @Log(title = "答卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QuestionnaireAnswer answer)
    {
        List<QuestionnaireAnswerVO> list = answerService.selectQuestionnaireAnswerVOList(answer);
        // 将details拼接为字符串，填充到answerSummary字段
        for (QuestionnaireAnswerVO vo : list) {
            if (vo.getDetails() != null && !vo.getDetails().isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (QuestionnaireAnswerDetail d : vo.getDetails()) {
                    sb.append(d.getQuestionTitle()).append(":").append(d.getOptionLabel()).append("; ");
                }
                vo.setAnswerSummary(sb.toString());
            }
        }
        ExcelUtil<QuestionnaireAnswerVO> util = new ExcelUtil<QuestionnaireAnswerVO>(QuestionnaireAnswerVO.class);
        util.exportExcel(response, list, "答卷数据");
    }

    /**
     * 获取答卷详细信息
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(answerService.selectQuestionnaireAnswerVOById(id));
    }

    /**
     * 新增答卷
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:add')")
    @Log(title = "答卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QuestionnaireAnswer answer)
    {
        return toAjax(answerService.insertQuestionnaireAnswer(answer));
    }

    /**
     * 修改答卷
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:edit')")
    @Log(title = "答卷", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QuestionnaireAnswer answer)
    {
        return toAjax(answerService.updateQuestionnaireAnswer(answer));
    }

    /**
     * 删除答卷
     */
    @PreAuthorize("@ss.hasPermi('questionnaire:answer:remove')")
    @Log(title = "答卷", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(answerService.deleteQuestionnaireAnswerByIds(ids));
    }

    /**
     * 根据问卷ID查询答卷列表
     */
    @GetMapping("/byQuestionnaire/{questionnaireId}")
    public AjaxResult getByQuestionnaire(@PathVariable("questionnaireId") Long questionnaireId)
    {
        List<QuestionnaireAnswer> list = answerService.selectAnswersByQuestionnaireId(questionnaireId);
        return success(list);
    }

    /**
     * 提交问卷答卷（公共接口，无需权限验证）
     */
    @PostMapping("/submit")
    public AjaxResult submitAnswer(@RequestBody QuestionnaireAnswer answer)
    {
        // 自动获取当前登录用户ID
        answer.setUserId(SecurityUtils.getUserId());
        return toAjax(answerService.submitQuestionnaireAnswer(answer));
    }

    /**
     * 提交问卷答卷（新接口，支持答案详情）
     */
    @PostMapping("/submitWithDetails")
    public AjaxResult submitAnswerWithDetails(@RequestBody QuestionnaireAnswerSubmitDTO submitDTO)
    {
        // 自动获取当前登录用户ID
        submitDTO.setUserId(SecurityUtils.getUserId());
        return toAjax(answerService.submitQuestionnaireAnswerWithDetails(submitDTO));
    }

    /**
     * 统计当前用户提交的答卷数量
     */
    @GetMapping("/my/count")
    public AjaxResult getMyAnswerCount() {
        Long userId = com.ruoyi.common.utils.SecurityUtils.getUserId();
        int count = answerService.countByUserId(userId);
        return success(count);
    }
} 